﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BaHuan.Entities;
using BaHuan.Common;
using BaHuan.BusinessLayer;
using BaHuan.Utils;

namespace BaHuan
{
    public partial class FrmPhieuChuyenKho : Form
    {
        private ChiNhanhCongTyMgt chinhanhctyMgt = new ChiNhanhCongTyMgt();
        private HangHoaManagement hanghoaMgt = new HangHoaManagement();
        private KhayDungManagement khaydungMgt = new KhayDungManagement();
        private PhieuChuyenKhoManagement phieuchuyenkhoMgt = new PhieuChuyenKhoManagement();        
        private CTPhieuChuyenKhoManagement ctphieuchuyenkhoMgt = new CTPhieuChuyenKhoManagement();
        private KhoManagement khoMgt = new KhoManagement();
        private QuanLyKhoManagement quanlykhoMgt = new QuanLyKhoManagement();
        private ButToanMgt buttoanMgt = new ButToanMgt();
        private DonViTinhMgt donvitinhMgt = new DonViTinhMgt();
        BangMaPhieuMgt bangmaphieuMgt = new BangMaPhieuMgt();

        public PhieuChuyenKho mphieuchuyenkho = new PhieuChuyenKho();
        private List<CTPhieuChuyenKho> lstDeleteCTPhieuChuyenKho = new List<CTPhieuChuyenKho>();
        public bool isEdited = false;
        private int iOldId = 0;

        private string sOldKhoXuat = "";
        private int IdLoaiPhieu = 9;

        private DateTime dtOld = new DateTime();
        private string prefixOld = "";

        private NhanVien nhanvien;        
        public NhanVien NhanVien
        {
            set { this.nhanvien = value; }
            get { return this.nhanvien; }
        }

        public FrmPhieuChuyenKho()
        {
            InitializeComponent();
        }

        private void dgvChiTiet_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        public void BindingToCbo()
        {
            cboKhoXuat.DataSource = GetAllChiNhanhCongTy();
            cboKhoXuat.DisplayMember = "TenChiNhanh";
            cboKhoXuat.ValueMember = "Id";

            cboKhoNhan.DataSource = GetAllChiNhanhCongTy();
            cboKhoNhan.DisplayMember = "TenChiNhanh";
            cboKhoNhan.ValueMember = "Id";

            cboDonViTinh.DataSource = GetAllDonViTinh();
            cboDonViTinh.DisplayMember = "TenDVT";
            cboDonViTinh.ValueMember = "TenDVT";


            cboPrefix.DataSource = GetAllBangMaPhieu(IdLoaiPhieu);
            cboPrefix.DisplayMember = "MaSo";
            cboPrefix.ValueMember = "Id";
        }

        public void LoadAll()
        {
            gpbThongTin.Enabled = false;
            dgvChiTiet.Enabled = false;

            btnSua.Enabled = false;
            btnXoa.Enabled = false;
            btnIn.Enabled = false;
            btnDinhKhoan.Enabled = false;
            btnLuu.Enabled = true;

            cboTenHang.DataSource = null;
            cboTenHang.DataSource = GetAllHangHoa();
            cboTenHang.DisplayMember = "Ten";
            cboTenHang.ValueMember = "MaSo";
         
            if (!isEdited)
            {
                //txtMaSo.Text = GetMaSoPhieuChuyenToan();
                txtNguoiLap.Text = this.nhanvien.HoTen;

                cboKhoNhan.SelectedIndex = 0;
                cboKhoXuat.SelectedIndex = 0;

                txtLyDo.Clear();
                lblId.Text = "";
                dtpNgay.Select();
            }
            else
            {
                btnSua.Enabled = true;
                btnXoa.Enabled = true;
                btnIn.Enabled = true;
                btnDinhKhoan.Enabled = true;
                btnLuu.Enabled = false;

                dtOld = this.mphieuchuyenkho.NgayThang;
                dtpNgay.Value = this.mphieuchuyenkho.NgayThang;

                prefixOld = mphieuchuyenkho.Prefix;
                cboPrefix.Text = mphieuchuyenkho.Prefix;
                txtMaSo.Text = this.mphieuchuyenkho.OrderNumber;  
              
                txtNguoiLap.Text = this.mphieuchuyenkho.NguoiLapPhieu;
                txtLyDo.Text = this.mphieuchuyenkho.LyDo;
                lblId.Text = this.mphieuchuyenkho.Id.ToString();

                cboKhoXuat.Text = this.mphieuchuyenkho.KhoXuat;
                cboKhoNhan.Text = this.mphieuchuyenkho.KhoNhan;

                iOldId = this.mphieuchuyenkho.Id;
                sOldKhoXuat = this.mphieuchuyenkho.KhoXuat;

                List<CTPhieuChuyenKho> lstCTphieuchuyenkho = (from p in GetAllCTPhieuChuyenKho()
                                                              where p.IdPhieuChuyenKho == this.mphieuchuyenkho.Id
                                                              select p).ToList();

                for (int i = 0; i < lstCTphieuchuyenkho.Count; i++)
                {
                    DataGridViewRow row = new DataGridViewRow();

                    DataGridViewComboBoxCell cboCell = new DataGridViewComboBoxCell();

                    List<HangHoa> lstHangThanhPham = GetAllHangHoa();
                    cboCell.DataSource = lstHangThanhPham;
                    cboCell.DisplayMember = "Ten";
                    cboCell.ValueMember = "MaSo";
                    cboCell.Value = lstCTphieuchuyenkho[i].MaHang;
                    row.Cells.Add(cboCell);

                    DataGridViewCell cell = new DataGridViewTextBoxCell();
                    cell.Value = lstCTphieuchuyenkho[i].MaHang;
                    row.Cells.Add(cell);

                    cboCell = new DataGridViewComboBoxCell();
                    cboCell.DataSource = GetAllDonViTinh();
                    cboCell.DisplayMember = "TenDVT";
                    cboCell.ValueMember = "TenDVT";
                    cboCell.Value = lstCTphieuchuyenkho[i].DonViTinh;
                    row.Cells.Add(cboCell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = lstCTphieuchuyenkho[i].SoLuong;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = lstCTphieuchuyenkho[i].DonGia;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = lstCTphieuchuyenkho[i].ThanhTien;
                    row.Cells.Add(cell);

                    cell = new DataGridViewTextBoxCell();
                    cell.Value = lstCTphieuchuyenkho[i].Id;
                    row.Cells.Add(cell);

                    dgvChiTiet.Rows.Add(row);
                }
            }
        }

        public void EditOrRemoveDinhKhoan(string MaSo)
        {
            ResultObj resultObj = new ResultObj();

            List<ButToan> lst = (from p in GetAllButToan()
                                 where p.SoChungTu == MaSo
                                 select p).ToList();

            if (lst.Count > 0)
            {
                foreach (ButToan b in lst)
                {
                    b.IsEdited = 1;
                    resultObj = buttoanMgt.UpdateButToan(b);
                }
            }
        }

        private void FrmPhieuChuyenKho_Load(object sender, EventArgs e)
        {
            BindingToCbo();
            LoadAll(); 
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            if (dgvChiTiet.Rows.Count > 1)
            {
                for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                {
                    if (dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString() == "" || dgvChiTiet.Rows[i].Cells[2].Value == null || dgvChiTiet.Rows[i].Cells[3].Value == null)
                    {
                        MessageBox.Show("Vui lòng nhập đầy đủ thông tin !","Thông báo");
                        return;
                    }
                }

                ResultObj resultObj = new ResultObj();

                PhieuChuyenKho phieuchuyenkho = new PhieuChuyenKho();
                phieuchuyenkho.Prefix = cboPrefix.Text;
                phieuchuyenkho.OrderNumber = txtMaSo.Text;
                phieuchuyenkho.MaSo = cboPrefix.Text + "/" + dtpNgay.Value.ToString("MM") + dtpNgay.Value.ToString("yy") + "/" + txtMaSo.Text;
                phieuchuyenkho.History = "";
                phieuchuyenkho.NgayThang = dtpNgay.Value;
                phieuchuyenkho.LyDo = txtLyDo.Text;
                phieuchuyenkho.NguoiLapPhieu = txtNguoiLap.Text;
                phieuchuyenkho.KhoXuat = (cboKhoXuat.Text != "" ? ((ChiNhanhCongTy)cboKhoXuat.SelectedItem).TenChiNhanh : "");
                phieuchuyenkho.KhoNhan = (cboKhoNhan.Text != "" ? ((ChiNhanhCongTy)cboKhoNhan.SelectedItem).TenChiNhanh : "");

                if (isEdited)
                {
                    List<CTPhieuChuyenKho> lst = (from p in GetAllCTPhieuChuyenKho()
                                                  where p.IdPhieuChuyenKho == iOldId
                                                  select p).ToList();

                    List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                    where q.SoChungTuXuat == phieuchuyenkho.MaSo
                                                    select q).ToList();

                    if (lstQuanLykho.Count > 0)
                    {
                        foreach (QuanLyKho q in lstQuanLykho)
                        {
                            q.IsDelete = 1;
                            resultObj = quanlykhoMgt.UpdateQuanLyKho(q);

                            HangHoa hanghoa = (from h in GetAllHangHoa()
                                               where h.Id == q.IdHangHoa && h.NoiLuuTru == sOldKhoXuat
                                               select h).FirstOrDefault();

                            int index = lst.FindIndex(p => p.MaHang == hanghoa.MaSo);
                            hanghoa.SoLuong += lst[index].SoLuong;
                            resultObj = hanghoaMgt.UpdateHangHoa(hanghoa);
                        }
                    }

                    phieuchuyenkho.Id = Convert.ToInt32(lblId.Text);
                    resultObj = phieuchuyenkhoMgt.UpdatePhieuChuyenKho(phieuchuyenkho);

                    for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                    {
                        CTPhieuChuyenKho ctPhieuChuyenKho = new CTPhieuChuyenKho();
                        ctPhieuChuyenKho.IdPhieuChuyenKho = phieuchuyenkho.Id;
                        ctPhieuChuyenKho.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                        ctPhieuChuyenKho.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                        ctPhieuChuyenKho.DonViTinh = dgvChiTiet.Rows[i].Cells[2].Value.ToString();
                        ctPhieuChuyenKho.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                        ctPhieuChuyenKho.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value.ToString());
                        ctPhieuChuyenKho.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());


                        if (dgvChiTiet.Rows[i].Cells[6].Value != null)
                        {
                            ctPhieuChuyenKho.Id = Convert.ToInt32(dgvChiTiet.Rows[i].Cells[6].Value);
                            resultObj = ctphieuchuyenkhoMgt.UpdateCTPhieuChuyenKho(ctPhieuChuyenKho);
                        }
                        else
                        {
                            resultObj = ctphieuchuyenkhoMgt.SaveNewCTPhieuChuyenKho(ctPhieuChuyenKho);
                            dgvChiTiet.Rows[i].Cells[6].Value = resultObj.ReturnCode;
                        }
                    }
                }
                else
                {
                    resultObj = phieuchuyenkhoMgt.SaveNewPhieuChuyenKho(phieuchuyenkho);

                    lblId.Text = resultObj.ReturnCode.ToString();

                    for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                    {
                        CTPhieuChuyenKho ctPhieuChuyenKho = new CTPhieuChuyenKho();
                        ctPhieuChuyenKho.IdPhieuChuyenKho = Convert.ToInt32(lblId.Text);
                        ctPhieuChuyenKho.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                        ctPhieuChuyenKho.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                        ctPhieuChuyenKho.DonViTinh = dgvChiTiet.Rows[i].Cells[2].Value.ToString();
                        ctPhieuChuyenKho.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                        ctPhieuChuyenKho.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value.ToString());
                        ctPhieuChuyenKho.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());

                        resultObj = ctphieuchuyenkhoMgt.SaveNewCTPhieuChuyenKho(ctPhieuChuyenKho);
                        dgvChiTiet.Rows[i].Cells[6].Value = resultObj.ReturnCode;
                    }
                }

                if (resultObj.ReturnCode > 0)
                {
                    MessageBox.Show("Lưu thành công", "Thông báo");

                    btnDinhKhoan.Enabled = true;
                    btnSua.Enabled = true;
                    btnXoa.Enabled = true;
                    btnIn.Enabled = true;
                    btnLuu.Enabled = false;

                    List<Kho> lstKho = (from k in GetAllKho()
                                        where k.TenKho == "155"
                                        select k).ToList();

                    //***insert quan ly kho cho Phieu Chuyen kho
                    List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                    where q.SoChungTuXuat == phieuchuyenkho.MaSo
                                                    select q).ToList();
                    
                    if (lstQuanLykho.Count <= 0)
                    {
                        for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
                        {
                            string maso = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                            HangHoa hanghoa = (from h in GetAllHangHoa()
                                               where h.MaSo == maso
                                               select h).FirstOrDefault();

                            if (lstKho.Count > 0 && hanghoa != null)
                            {
                                QuanLyKho quanlykho = new QuanLyKho();
                                quanlykho.IdKho = lstKho[0].Id;
                                quanlykho.IdHangHoa = hanghoa.Id;
                                quanlykho.SoChungTuNhap = "";
                                quanlykho.SoChungTuXuat = phieuchuyenkho.MaSo;

                                resultObj = quanlykhoMgt.SaveNewQuanLyKho(quanlykho);

                                hanghoa.SoLuong -= Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value);
                                resultObj = hanghoaMgt.UpdateHangHoa(hanghoa);
                            }
                        }
                    }

                    //delete cac CTPhieuChuyenKho do nguoi dung chuot phai "XOA"
                    if (this.lstDeleteCTPhieuChuyenKho.Count > 0)
                    {
                        foreach (CTPhieuChuyenKho ct in this.lstDeleteCTPhieuChuyenKho)
                        {
                            ct.IsDelete = 1;
                            ctphieuchuyenkhoMgt.UpdateCTPhieuChuyenKho(ct);
                        }
                    }
                }
                else if (resultObj.ReturnCode == Definitions.DUPLICATED_VALUE)
                    MessageBox.Show("Dữ liệu bị trùng", "Thông báo");
                else
                    MessageBox.Show("Thất bại");
            }
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            isEdited = true;
            gpbThongTin.Enabled = true;
            dgvChiTiet.Enabled = true;

            btnSua.Enabled = false;
            btnXoa.Enabled = false;
            btnIn.Enabled = false;
            btnDinhKhoan.Enabled = false;
            btnLuu.Enabled = true;
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            DialogResult result;
            result = MessageBox.Show("Bạn có chắc chắn muốn xóa chứng từ này không?", "Xóa phiếu chuyển kho", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                ResultObj resultObj = new ResultObj();

                PhieuChuyenKho phieuchuyenkho = new PhieuChuyenKho();
                phieuchuyenkho.MaSo = txtMaSo.Text;
                phieuchuyenkho.NgayThang = dtpNgay.Value;
                phieuchuyenkho.LyDo = txtLyDo.Text;
                phieuchuyenkho.NguoiLapPhieu = txtNguoiLap.Text;
                phieuchuyenkho.KhoXuat = (cboKhoXuat.Items.Count > 0 ? ((ChiNhanhCongTy)cboKhoXuat.SelectedItem).TenChiNhanh : "");
                phieuchuyenkho.KhoNhan = (cboKhoNhan.Items.Count > 0 ? ((ChiNhanhCongTy)cboKhoNhan.SelectedItem).TenChiNhanh : "");
                phieuchuyenkho.IsDelete = 1;
                phieuchuyenkho.Id = Convert.ToInt32(lblId.Text);

                resultObj = phieuchuyenkhoMgt.UpdatePhieuChuyenKho(phieuchuyenkho);

                List<CTPhieuChuyenKho> lst = (from p in GetAllCTPhieuChuyenKho()
                                              where p.IdPhieuChuyenKho == phieuchuyenkho.Id
                                              select p).ToList();

                foreach (CTPhieuChuyenKho ct in lst)
                {
                    ct.IsDelete = 1;
                    resultObj = ctphieuchuyenkhoMgt.UpdateCTPhieuChuyenKho(ct);
                }

                EditOrRemoveDinhKhoan(phieuchuyenkho.MaSo);

                List<QuanLyKho> lstQuanLykho = (from q in GetAllQuanLyKho()
                                                where q.SoChungTuXuat == phieuchuyenkho.MaSo
                                                select q).ToList();

                if (lstQuanLykho.Count > 0)
                {
                    foreach (QuanLyKho q in lstQuanLykho)
                    {
                        q.IsDelete = 1;
                        resultObj = quanlykhoMgt.UpdateQuanLyKho(q);

                        HangHoa hanghoa = (from h in GetAllHangHoa()
                                           where h.Id == q.IdHangHoa && h.NoiLuuTru == phieuchuyenkho.KhoXuat
                                           select h).FirstOrDefault();

                        int index = lst.FindIndex(p => p.MaHang == hanghoa.MaSo);
                        hanghoa.SoLuong += lst[index].SoLuong;
                        resultObj = hanghoaMgt.UpdateHangHoa(hanghoa);
                    }
                }

                MessageBox.Show("Đã xóa", "Thông báo!");

                btnDinhKhoan.Enabled = false;
                btnSua.Enabled = false;
                btnXoa.Enabled = false;
                btnIn.Enabled = false;
                btnLuu.Enabled = true;
            }
        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            FrmXemReport frm = new FrmXemReport(mphieuchuyenkho);
            this.Hide();
            frm.ShowDialog();
            this.Show();
        } 

        private void btnThem_Click(object sender, EventArgs e)
        {
            prefixOld = "";
            dtOld = new DateTime();

            isEdited = false;
            LoadAll();

            gpbThongTin.Enabled = true;
            dgvChiTiet.Enabled = true;
            dgvChiTiet.Rows.Clear();
        }

        private void btnDinhKhoan_Click(object sender, EventArgs e)
        {
            PhieuChuyenKho phieuchuyenkho = new PhieuChuyenKho();
            phieuchuyenkho.Prefix = cboPrefix.Text;
            phieuchuyenkho.OrderNumber = txtMaSo.Text;
            phieuchuyenkho.MaSo = cboPrefix.Text + "/" + dtpNgay.Value.ToString("MM") + dtpNgay.Value.ToString("yy") + "/" + txtMaSo.Text;
            phieuchuyenkho.History = "";
            phieuchuyenkho.LyDo = txtLyDo.Text;
            phieuchuyenkho.NguoiLapPhieu = txtNguoiLap.Text;
            phieuchuyenkho.KhoXuat = ((ChiNhanhCongTy)cboKhoXuat.SelectedItem).TenChiNhanh;
            phieuchuyenkho.KhoNhan = ((ChiNhanhCongTy)cboKhoNhan.SelectedItem).TenChiNhanh;
            phieuchuyenkho.listCTPhieuChuyenKho = new List<CTPhieuChuyenKho>();
            long tien = 0;

            for (int i = 0; i < dgvChiTiet.Rows.Count - 1; i++)
            {
                CTPhieuChuyenKho ctPhieuChuyenKho = new CTPhieuChuyenKho();
               
                ctPhieuChuyenKho.TenHang = dgvChiTiet.Rows[i].Cells[0].FormattedValue.ToString();
                ctPhieuChuyenKho.MaHang = dgvChiTiet.Rows[i].Cells[1].Value.ToString();
                ctPhieuChuyenKho.DonViTinh = dgvChiTiet.Rows[i].Cells[2].Value.ToString();
                ctPhieuChuyenKho.SoLuong = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[3].Value.ToString());
                ctPhieuChuyenKho.DonGia = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[4].Value.ToString());
                ctPhieuChuyenKho.ThanhTien = Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value.ToString());
                tien += Convert.ToInt64(dgvChiTiet.Rows[i].Cells[5].Value);
                phieuchuyenkho.listCTPhieuChuyenKho.Add(ctPhieuChuyenKho);
            }

            FrmDinhKhoanPhieuChuyenKho frmDinhKhoanPhieuChuyenKho = new FrmDinhKhoanPhieuChuyenKho(tien);
            frmDinhKhoanPhieuChuyenKho.PhieuChuyenKho = phieuchuyenkho;
            frmDinhKhoanPhieuChuyenKho.ShowDialog();
        }

        private void dgvChiTiet_Enter(object sender, EventArgs e)
        {
            if (dgvChiTiet.CurrentRow != null)
            {
                dgvChiTiet.CurrentCell = dgvChiTiet.Rows[dgvChiTiet.CurrentRow.Index].Cells[0];
            }
        }

        private void XoaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvChiTiet.CurrentRow != null)
            {
                if (dgvChiTiet.CurrentRow.Index != (dgvChiTiet.Rows.Count - 1))
                {
                    if (dgvChiTiet.CurrentRow.Cells[6].Value != null)
                    {
                        int id = Convert.ToInt32(dgvChiTiet.CurrentRow.Cells[6].Value.ToString());

                        CTPhieuChuyenKho ctPhieuChuyenKho = (from ct in GetAllCTPhieuChuyenKho()
                                                             where ct.Id == id
                                                             select ct).FirstOrDefault();

                        if (ctPhieuChuyenKho != null)
                        {
                            if (!lstDeleteCTPhieuChuyenKho.Contains(ctPhieuChuyenKho))
                                lstDeleteCTPhieuChuyenKho.Add(ctPhieuChuyenKho);
                        }
                    }

                    dgvChiTiet.Rows.RemoveAt(dgvChiTiet.CurrentRow.Index);
                }
            }
        }

        private void dgvChiTiet_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                DataGridView.HitTestInfo hti = dgvChiTiet.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    dgvChiTiet.ClearSelection();
                    dgvChiTiet.CurrentCell = dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    dgvChiTiet.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }

        private void dgvChiTiet_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex > -1)
                {
                    if (e.ColumnIndex == 0)
                    {
                        dgvChiTiet.Rows[e.RowIndex].Cells[1].Value = dgvChiTiet.Rows[e.RowIndex].Cells[0].Value.ToString();

                        HangHoa hanghoa = (from htp in GetAllHangHoa()
                                           where htp.MaSo == dgvChiTiet.Rows[e.RowIndex].Cells[0].Value.ToString()
                                           select htp).FirstOrDefault();

                        dgvChiTiet.Rows[e.RowIndex].Cells[4].Value = hanghoa.DonGia;
                    }

                    if (e.ColumnIndex == 1)
                    {
                        HangHoa hanghoa = (from htp in GetAllHangHoa()
                                           where htp.MaSo == dgvChiTiet.Rows[e.RowIndex].Cells[1].Value.ToString()
                                           select htp).FirstOrDefault();

                        if (hanghoa.Id != -1)
                        {
                            dgvChiTiet.Rows[e.RowIndex].Cells[4].Value = hanghoa.DonGia;
                            dgvChiTiet.Rows[e.RowIndex].Cells[0].Value = hanghoa.MaSo;
                        }
                        else return;
                    }

                    if (e.ColumnIndex == 2)
                    {
                        if (dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
                        {
                            MessageBox.Show("Vui lòng chọn đơn vị tính !", "Thông báo");
                            return;
                        }
                    }

                    if (e.ColumnIndex == 3 || e.ColumnIndex == 4 || e.ColumnIndex == 5)
                    {
                        long num;
                        if (dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
                            dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                        if (!Int64.TryParse(dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out num))
                        {
                            MessageBox.Show("Vui lòng nhập số !", "Thông báo");
                            dgvChiTiet.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                            return;
                        }
                        if (dgvChiTiet.Rows[e.RowIndex].Cells[0].Value == null && dgvChiTiet.Rows[e.RowIndex].Cells[1].Value == null)
                        {
                            MessageBox.Show("Bạn chưa chọn Tên Hàng", "Thông tin");
                            return;
                        }
                    }

                    if (e.ColumnIndex == 3 || e.ColumnIndex == 4)
                    {

                        long soluong = 0;
                        long dongia = 0;

                        if (dgvChiTiet.Rows[e.RowIndex].Cells[3].Value != null)
                        {
                            try
                            {
                                dgvChiTiet.Rows[e.RowIndex].Cells[1].ReadOnly = true;
                                if (dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString() != "")
                                {
                                    soluong = Convert.ToInt64(dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString());
                                    if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "cây")
                                        dgvChiTiet.Rows[e.RowIndex].Cells[5].Value = (soluong * 300).ToString();
                                    else if (dgvChiTiet.Rows[e.RowIndex].Cells[2].Value.ToString().ToLower() == "khay")
                                    {
                                        List<HangHoa> lstHangThanhPham = (from htp in GetAllHangHoa()
                                                                          where htp.MaSo == dgvChiTiet.Rows[e.RowIndex].Cells[1].Value.ToString()
                                                                          select htp).ToList();
                                        dgvChiTiet.Rows[e.RowIndex].Cells[1].ReadOnly = true;
                                        List<KhayDung> lstKhayDung = (from kd in GetAllKhayDung()
                                                                      where kd.Id == lstHangThanhPham[0].IdKhayDung
                                                                      select kd).ToList();
                                        dgvChiTiet.Rows[e.RowIndex].Cells[5].Value = (lstKhayDung[0].SoLuongHop * soluong).ToString();
                                    }
                                    else
                                        dgvChiTiet.Rows[e.RowIndex].Cells[5].Value = dgvChiTiet.Rows[e.RowIndex].Cells[3].Value.ToString();
                                }
                                else
                                {
                                    soluong = 0;
                                    dgvChiTiet.Rows[e.RowIndex].Cells[3].Value = "0";
                                }
                            }
                            catch
                            {
                            }
                        }

                        dongia = Convert.ToInt64(dgvChiTiet.Rows[e.RowIndex].Cells[4].Value.ToString());
                        long thanhtien = soluong * dongia;
                        dgvChiTiet.Rows[e.RowIndex].Cells[5].Value = thanhtien.ToString();
                        dgvChiTiet.Rows[e.RowIndex].Cells[5].ReadOnly = true;
                        dgvChiTiet.Rows[e.RowIndex].Cells[1].ReadOnly = true;
                        //dgvChiTiet.Rows[e.RowIndex].Cells[4].ReadOnly = true;
                        btnLuu.Enabled = true;
                    }
                }
            }
            catch
            {
            }
        }

        private void cboPrefix_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (prefixOld != ((BangMaPhieu)cboPrefix.SelectedItem).MaSo)
                txtMaSo.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, IdLoaiPhieu, dtpNgay.Value);
        }

        private void dtpNgay_ValueChanged(object sender, EventArgs e)
        {
            if (dtOld != dtpNgay.Value)
                txtMaSo.Text = cboPrefix.Text == "" ? "" : KiemTraMaSo.CheckCode(((BangMaPhieu)cboPrefix.SelectedItem).MaSo, IdLoaiPhieu, dtpNgay.Value);
        }

        private void cboKhoXuat_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhCongTy b in cboKhoXuat.Items)
            {
                if (b.TenChiNhanh.ToLower().Contains(cboKhoXuat.Text)&& cboKhoXuat.Text!="")
                {
                    cboKhoXuat.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboKhoXuat.SelectedValue == null)
            {
                cboKhoXuat.Text = "";
                cboKhoXuat.Focus();
            }
        }

        private void cboKhoNhan_Leave(object sender, EventArgs e)
        {
            foreach (ChiNhanhCongTy b in cboKhoNhan.Items)
            {
                if (b.TenChiNhanh.ToLower().Contains(cboKhoNhan.Text) && cboKhoNhan.Text!="")
                {
                    cboKhoNhan.SelectedValue = b.Id;
                    break;
                }
            }

            if (cboKhoNhan.SelectedValue == null)
            {
                cboKhoNhan.Text = "";
                cboKhoNhan.Focus();
            }
        }

        public List<PhieuChuyenKho> GetAllPhieuChuyenKho()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = phieuchuyenkhoMgt.GetAllPhieuChuyenKho();
            List<PhieuChuyenKho> listPhieuChuyenKho = (List<PhieuChuyenKho>)resultObj.Result;

            return listPhieuChuyenKho;
        }

        public List<CTPhieuChuyenKho> GetAllCTPhieuChuyenKho()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = ctphieuchuyenkhoMgt.GetAllCTPhieuChuyenKho();
            List<CTPhieuChuyenKho> listCTPhieuChuyenKho = (List<CTPhieuChuyenKho>)resultObj.Result;

            return listCTPhieuChuyenKho;
        }

        public List<ChiNhanhCongTy> GetAllChiNhanhCongTy()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = chinhanhctyMgt.GetAllChiNhanhCongTy();
            List<ChiNhanhCongTy> listChiNhanhCongTy = (List<ChiNhanhCongTy>)resultObj.Result;

            return listChiNhanhCongTy;
        }

        public List<HangHoa> GetAllHangHoa()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = hanghoaMgt.GetAllHangHoa();
            List<HangHoa> listHangThanhPham = (List<HangHoa>)resultObj.Result;

            return listHangThanhPham;
        }

        public List<KhayDung> GetAllKhayDung()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = khaydungMgt.GetAllKhayDung();
            List<KhayDung> listKhayDung = (List<KhayDung>)resultObj.Result;

            return listKhayDung;
        }

        public List<Kho> GetAllKho()
        {
            ResultObj resultObj = new ResultObj();
            List<Kho> lstKho = new List<Kho>();

            resultObj = khoMgt.GetAllKho();
            lstKho = (List<Kho>)resultObj.Result;

            return lstKho;
        }

        public List<DonViTinh> GetAllDonViTinh()
        {
            ResultObj resultObj = new ResultObj();
            List<DonViTinh> lstDVT = new List<DonViTinh>();

            resultObj = donvitinhMgt.GetAllDonViTinh();
            lstDVT = (List<DonViTinh>)resultObj.Result;

            return lstDVT;
        }

        public List<ButToan> GetAllButToan()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = buttoanMgt.GetAllButToan();
            List<ButToan> listButToan = (List<ButToan>)resultObj.Result;

            return listButToan;
        }

        public List<QuanLyKho> GetAllQuanLyKho()
        {
            ResultObj resultObj = new ResultObj();
            List<QuanLyKho> lstQuanLyKho = new List<QuanLyKho>();

            resultObj = quanlykhoMgt.GetAllQuanLyKho();
            lstQuanLyKho = (List<QuanLyKho>)resultObj.Result;

            return lstQuanLyKho;
        }

        public List<BangMaPhieu> GetAllBangMaPhieu(int id)
        {
            ResultObj resultObj = new ResultObj();

            resultObj = bangmaphieuMgt.GetAllBangMaPhieuByIDLoaiPhieu(id);
            List<BangMaPhieu> listBangMaPhieu = (List<BangMaPhieu>)resultObj.Result;

            return listBangMaPhieu;
        }
    }
}
